package com.elastic.eslearn._2_doc;

import com.elastic.eslearn._0_client.EsUtils;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.index.reindex.DeleteByQueryRequestBuilder;
import org.elasticsearch.script.Script;

import java.io.IOException;

/**
 * 文档管理
 */
public class DocAdmin {
	public String indexName = "twitter";
	public String typeName = "_doc";
	public static void main(String[] args) throws Exception {
		TransportClient client = EsUtils.getSingleClient();
		DocAdmin docAdmin = new DocAdmin();
		docAdmin.getDoc(client);
		docAdmin.deleteDoc(client);
		docAdmin.updateDoc(client);
		docAdmin.updateDocByScript(client);
		docAdmin.upsertDoc(client);
		docAdmin.deleteByQuery(client);
		docAdmin.multiGet(client);
		docAdmin.buldRequrest(client);
	}

	/**
	 * 获取文档
	 * @param client
	 */
	public void getDoc(TransportClient client) {
		GetResponse response = client.prepareGet(indexName, typeName, "1").get();
		String content = response.getSourceAsString();
		System.out.println(content);
		if (response.isExists()) {
			System.out.println(response.getIndex());
			System.out.println(response.getType());
			System.out.println(response.getId());
			System.out.println(response.getVersion());
			System.out.println(response.getSourceAsMap());
		} else {
			System.out.println("not find doc");
		}
	}

	/**
	 * 删除文档
	 * @param client
	 */
	public void deleteDoc(TransportClient client) {
		DeleteResponse response = client.prepareDelete(indexName, typeName, "1").get();
		System.out.println(response.status());
	}

	/**
	 * 更新文档
	 * @param client
	 * @throws Exception
	 */
	public void updateDoc(TransportClient client) throws Exception {
		UpdateRequest updateRequest = new UpdateRequest();
		updateRequest.index(indexName);
		updateRequest.type(typeName);
		updateRequest.id("2");
		updateRequest.doc(XContentFactory.jsonBuilder()
				.startObject()
				.field("gender", "male")
				.endObject()
		);
		client.update(updateRequest).get();
		System.out.println("update success");
	}

	/**
	 * 更新文档, 也支持执行脚本
	 * @param client
	 * @throws Exception
	 */
	public void updateDocByScript(TransportClient client) throws Exception {
		UpdateRequest updateRequest = new UpdateRequest(indexName, typeName, "2");
		updateRequest.script(new Script("ctx._source.gender = \"male\""));
		client.update(updateRequest).get();
		System.out.println("update by script success");
	}

	/**
	 * 如果文档存在就更新，如果不存在就新建
	 * @param client
	 */
	public void upsertDoc(TransportClient client) throws IOException {
		IndexRequest indexRequest = new IndexRequest(indexName, typeName, "1")
				.source(XContentFactory.jsonBuilder()
						.startObject()
						.field("name", "Joe Smith")
						.field("gender", "male")
						.endObject()
				);
		UpdateRequest updateRequest = new UpdateRequest(indexName, typeName, "1");
		updateRequest.doc(XContentFactory.jsonBuilder()
				.startObject()
				.field("gender", "male")
				.endObject()
		).upsert(indexRequest);
		client.update(updateRequest).actionGet();
		System.out.println("upsert success");
	}

	/**
	 * delete by Query  查询删除
	 * @param client
	 */
	public void deleteByQuery(TransportClient client) {
		BulkByScrollResponse response = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE)
				.filter(QueryBuilders.matchQuery("title", "java"))
				.source("books")
				.get();
		long deleted = response.getDeleted();
		System.out.println("delete success : " + deleted);
	}

	/**
	 * 批量获取，同时查询逗哥索引，多个文档
	 * @param client
	 */
	public void multiGet(TransportClient client) {
		MultiGetResponse multiGetResponse = client.prepareMultiGet()
				.add(indexName, typeName, "1")
				.add(indexName, typeName, "2", "3", "4")
				.add("books", typeName, "1")
				.get();
		for(MultiGetItemResponse itemResponse : multiGetResponse) {
			GetResponse response = itemResponse.getResponse();
			if(response != null && response.isExists()) {
				String json = response.getSourceAsString();
				System.out.println(json);
			}
		}
	}

	/**
	 * 批量操作
	 * @param client
	 */
	public void buldRequrest(TransportClient client) throws Exception {
		BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
		IndexRequestBuilder indexRequest = client.prepareIndex(indexName, typeName, "5")
				.setSource(XContentFactory.jsonBuilder()
						.startObject()
						.field("user", "kimchy")
						.field("postDate", "2013-01-30")
						.field("message", "trying out Elasticsearch")
						.endObject()
				);
		DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete(indexName, typeName, "2");
		UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(indexName, typeName, "5")
				.setDoc(XContentFactory.jsonBuilder()
						.startObject()
						.field("message", "update Bulk request")
						.endObject()
				);
		bulkRequestBuilder.add(indexRequest)
				.add(deleteRequestBuilder)
				.add(updateRequestBuilder)
				.execute()
				.actionGet();
		System.out.println("批量操作完成");
	}

}
